<template>
  <div class="customer-company">
    <h1>企事业单位客户（列表）</h1>
    <div class="table-container">
      <el-table :data="customerList" style="width: 100%" border>
        <el-table-column prop="id" label="客户ID" width="80" />
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="type" label="客户类型" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="editCustomer(scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteCustomer(scope.row)"
              :disabled="scope.row.deleted === 1">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 编辑客户信息对话框 -->
    <el-dialog title="编辑客户信息" v-model="editDialogVisible" width="500px">
      <el-form :model="editingCustomer" label-width="100px">
        <el-form-item label="客户名称">
          <el-input v-model="editingCustomer.customerName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editingCustomer.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="editingCustomer.address"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCustomer">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getCustomerInfoAPI, updateCustomerStatusAPI, deleteCustomerAPI, updateCustomerAPI } from '@/apis/user'

export default {
  name: 'CustomerCompany',
  data() {
    return {
      customerList: [],
    editDialogVisible: false,
    editingCustomer: {
      id: null,
      customerName: '',
      phone: '',
      address: ''
    }
    }
  },
  methods: {
    // 编辑客户信息
    editCustomer(row) {
      this.editingCustomer = {
        id: row.id,
        customerName: row.customerName,
        phone: row.phone,
        address: row.address
      }
      this.editDialogVisible = true
    },
    
    // 保存客户信息
    async saveCustomer() {
      try {
        await updateCustomerAPI(this.editingCustomer)
        
        // 更新前端列表中的数据
        const index = this.customerList.findIndex(item => item.id === this.editingCustomer.id)
        if (index > -1) {
          this.customerList[index].customerName = this.editingCustomer.customerName
          this.customerList[index].phone = this.editingCustomer.phone
          this.customerList[index].address = this.editingCustomer.address
          
          // 更新时间
          const now = new Date()
          this.customerList[index].updateTime = now.getFullYear() + '-' +
                          String(now.getMonth() + 1).padStart(2, '0') + '-' +
                          String(now.getDate()).padStart(2, '0') + ' ' +
                          String(now.getHours()).padStart(2, '0') + ':' +
                          String(now.getMinutes()).padStart(2, '0') + ':' +
                          String(now.getSeconds()).padStart(2, '0')
        }
        
        this.editDialogVisible = false
        this.$message({
          type: 'success',
          message: '客户信息更新成功!'
        })
      } catch (error) {
        console.error('更新客户信息失败:', error)
        this.$message({
          type: 'error',
          message: '更新客户信息失败: ' + (error.message || error.msg || '未知错误')
        })
      }
    },
    
    getStatusType(status) {
      switch (status) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        case 2:
          return 'info'
        default:
          return 'info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 0:
          return '禁用'
        case 1:
          return '启用'
        case 2:
          return '删除'
        default:
          return '未知'
      }
    },
    // 切换客户状态
    async toggleStatus(row) {
      try {
        // 准备发送到后端的数据
        const requestData = {
          id: row.id,
          status: row.status === 1 ? 0 : 1 // 切换状态：启用(1) <-> 禁用(0)
        }

        // 调用后端接口更新状态
        await updateCustomerStatusAPI(requestData)

        // 后端更新成功后，再更新前端状态
        row.status = requestData.status

        // 更新时间
        const now = new Date()
        row.updateTime = now.getFullYear() + '-' +
                        String(now.getMonth() + 1).padStart(2, '0') + '-' +
                        String(now.getDate()).padStart(2, '0') + ' ' +
                        String(now.getHours()).padStart(2, '0') + ':' +
                        String(now.getMinutes()).padStart(2, '0') + ':' +
                        String(now.getSeconds()).padStart(2, '0')

        this.$message({
          type: 'success',
          message: `${requestData.status === 1 ? '启用' : '禁用'}成功!`
        })
      } catch (error) {
        console.error('更新客户状态失败:', error)
        this.$message({
          type: 'error',
          message: '更新客户状态失败: ' + (error.message || error.msg || '未知错误')
        })
      }
    },
    // 逻辑删除客户
    deleteCustomer(row) {
      // 删除客户（逻辑删除，将deleted字段设置为1）
      this.$confirm('此操作将删除该客户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用后端接口进行逻辑删除
          await deleteCustomerAPI(row.id)

          // 后端删除成功后，从前端列表中移除该记录
          const index = this.customerList.findIndex(item => item.id === row.id)
          if (index > -1) {
            this.customerList.splice(index, 1)
          }

          // 更新时间
          const now = new Date()
          row.updateTime = now.getFullYear() + '-' +
                          String(now.getMonth() + 1).padStart(2, '0') + '-' +
                          String(now.getDate()).padStart(2, '0') + ' ' +
                          String(now.getHours()).padStart(2, '0') + ':' +
                          String(now.getMinutes()).padStart(2, '0') + ':' +
                          String(now.getSeconds()).padStart(2, '0')

          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } catch (error) {
          console.error('删除客户失败:', error)
          this.$message({
            type: 'error',
            message: '删除客户失败: ' + (error.message || error.msg || '未知错误')
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取所有客户信息，并筛选企事业类型客户
    async getAllCustomers() {
      try {
        const res = await getCustomerInfoAPI()
        // 确保正确处理返回的数据
        if (res && res.data) {
          // 筛选企事业类型客户（根据type字段筛选），并过滤掉已删除的客户
          this.customerList = res.data.filter(customer =>
            customer.type === '企事业客户' && customer.deleted !== 1
          )
        } else if (res instanceof Array) {
          // 筛选企事业类型客户，并过滤掉已删除的客户
          this.customerList = res.filter(customer =>
            customer.type === '企事业客户' && customer.deleted !== 1
          )
        } else {
          this.customerList = []
        }
      } catch (error) {
        console.error('获取客户信息失败:', error)
        this.$message({
          type: 'error',
          message: '获取客户信息失败: ' + (error.message || error.msg || '未知错误')
        })
        // 发生错误时设置为空数组，避免页面空白
        this.customerList = []
      }
    }
  },
  mounted() {
    // 页面加载时获取所有客户信息
    this.getAllCustomers()
  }
}
</script>

<style scoped>
.customer-company {
  padding: 20px;
  background-color: #f5f5f5;
}

.customer-company h1 {
  margin-top: 0;
  color: #2c3e50;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
}
</style>
